package com.zhentao.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.api.article.ArticleClientApi;
import com.zhentao.common.tess4j.Tess4jClient;
import com.zhentao.file.service.FileStorageService;
import com.zhentao.mapper.WmChannelMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmSensitiveMapper;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.article.dto.ArticleDto;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.pojo.WmChannel;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.model.wemedia.pojo.WmUser;
import com.zhentao.model.wemedia.pojos.WmSensitive;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.utils.aliyun.TextAutoRoute;
import com.zhentao.utils.common.SensitiveWordUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private ArticleClientApi articleClientApi;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @SneakyThrows
    @Override
    @Async
    @Transactional
    public void autoScanWmNews(Integer id) {
        //1.根据文章的id查询到文章的标题+内容然后进行审核
        WmNews wmNews = wmNewsMapper.selectById(id);
        String content = wmNews.getTitle() + wmNews.getContent();
        //2.进行审核
        ResponseResult result = TextAutoRoute.isGreenText(content);
        if (result.getCode() != 200) {
            //审核状态修改成审核失败
            wmNews.setStatus((short) 2);
            wmNews.setReason(result.getErrorMessage() + ";" + result.getData());
            wmNewsMapper.updateById(wmNews);
        } else { //审核通过，状态修改为审核成功
            wmNews.setStatus((short) 8);
            wmNewsMapper.updateById(wmNews);
            //如何审核成功，继续进行后续操作

            //调用远程接口进行文章的保存
            saveApArticle(wmNews);
        }
    }

    public ResponseResult saveApArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //拷贝属性
        BeanUtils.copyProperties(wmNews, dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }

        //自管理的敏感词过滤
        String content = wmNews.getContent();
        boolean isSensitive = handleSensitiveScan(content.toString(), wmNews);
        if (!isSensitive) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        ResponseResult result = articleClientApi.saveArticle(dto);

        //如果发布-保存成功，绑定news的articleId 和状态
        if (result.getCode() == 200) {
            wmNews.setStatus((short) 9); //已发布
            wmNews.setReason("审核成功");
            wmNews.setArticleId((Long) result.getData());
            wmNewsMapper.updateById(wmNews);
        }
        return ResponseResult.okResult("发布成功");
    }

    /**
     * 自管理的敏感词审核
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {

        boolean flag = true;

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容" + map);
            flag = false;
        }

        return flag;
    }

    /**
     * 修改文章内容
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }
}